using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AnnouncementsManager : MonoBehaviour
{
    public static AnnouncementsManager Instance;

    [SerializeField] private GameObject announcementPrefab;
    [SerializeField] private Transform announcementBox;

    private List<AnnouncementPair> activePairs = new List<AnnouncementPair>();

    void Awake()
    {
        if (Instance == null) Instance = this;
        else Destroy(gameObject);
    }

    public AnnouncementPair CreatePair(string npcName, string locationName)
    {
        // Create NPC announcement
        GameObject npcObj = Instantiate(announcementPrefab, announcementBox);
        AnnouncementUI npcUI = npcObj.GetComponent<AnnouncementUI>();
        npcUI.SetMessage("Generating NPC: " + npcName);

        // Create Background announcement
        GameObject bgObj = Instantiate(announcementPrefab, announcementBox);
        AnnouncementUI bgUI = bgObj.GetComponent<AnnouncementUI>();
        bgUI.SetMessage("Generating Background: " + locationName);

        AnnouncementPair pair = new AnnouncementPair(npcUI, bgUI);
        activePairs.Add(pair);
        return pair;
    }

    public void MarkAsLoaded(AnnouncementUI ui)
    {
        ui.SetLoaded(true);

        AnnouncementPair pair = activePairs.Find(p => p.Contains(ui));
        if (pair == null) return;

        // If both images done OR one failed (missing texture but callback fired), remove
        if (pair.IsReady() || (ui.IsLoaded && ui.gameObject == null))
        {
            StartCoroutine(RemovePairAfterDelay(pair, 3f));
        }
    }


    public IEnumerator RemovePairAfterDelay(AnnouncementPair pair, float delay)
    {
        yield return new WaitForSeconds(delay);

        if (pair != null)
        {
            activePairs.Remove(pair);
            pair.DestroyBoth();
        }
    }
}
